/**
 * Kick
 * <p/>
 * User: druttis
 * Date: 2013-03-13
 * Time: 00:03
 */
package org.dru.masic.synths.kick {
import org.dru.masic.MasicComponent;
import org.dru.masic.MasicConstants;
import org.dru.masic.MasicOutput;
import org.dru.stk.StkEnvelope;
import org.dru.stk.StkMath;

public final class Kick extends MasicComponent {
    private var _out: MasicOutput;
    private var _envelope: StkEnvelope;
    private var _phase: Number;
    private var _rate: Number;
    private var _velocity: Number;

    public function Kick() {
        _out = createOutput("out", false);
        _envelope = new StkEnvelope();
        _envelope.attack = 1.0;
        _envelope.decay = 0.15 / 441.0;
        _envelope.sustain = 0.0;
        _envelope.release = 1.0 / 882.0;
        _phase = 0.0;
        _rate = -1;
    }

    override public function processNote(note: int, velocity: Number): void {
        _envelope.gate = false;
        if (velocity > 0) {
            _envelope.gate = true;
            _phase = 0.0;
            _rate = 40.0 / Number(MasicConstants.SAMPLE_RATE);
            _velocity = velocity;
        }
    }

    override public function processSamples(start: int, end: int): void {
        if (_rate != -1) {
            for (var pos: int = start; pos < end; pos++) {
                const env_out: Number = _envelope.next();
                _out.left[pos] = (_phase >= 0.5 ? 1.0 : -1.0) * _velocity * env_out * 2.0;
                _phase = StkMath.clamp(_phase + _rate + _rate * 2.0 * env_out);
            }
            if (_envelope.idle) {
                _rate = -1;
            }
        }
    }
}
}
